﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EzDesk.Core.Model;
using EzDesk.Core.ServiceImpl.Repositories.Interface;

namespace EzDesk.Core.ServiceImpl.Repositories
{
    public class DeptRepository : IDeptRepository, IRepository<Dept>
    {
        private EzDeskDataContext _db;

        public DeptRepository(EzDeskDataContext db)
        {
            this._db = db;
        }


        #region IRepository<Dept> Members

        public void SaveChanges()
        {
            _db.SubmitChanges();
        }

        public Guid Add(Dept model, bool saveChanges = true)
        {
            var entity = model.ToEntity();
            _db.ez_Depts.InsertOnSubmit(entity);
            if (saveChanges)
            {
                SaveChanges();
            }

            return entity.DeptId;
        }
    

        public Dept GetById(Guid id)
        {
            Dept dept = null;
            if (id != null)
            {
                dept = _db.ez_Depts.Where(p => p.DeptId == id)
                    .SingleOrDefault()
                    .ToModel();
            }
            return dept;
        }

        public IQueryable<Dept> GetAll()
        {
            return from dept in _db.ez_Depts
                   let ezGroup = dept.ez_Group.ToModel()
                   select new Dept()
                   {
                       Id = dept.DeptId,
                       DeptName = dept.DeptName,
                       GroupId = dept.GroupId,
                   };
        }

        public void Delete(Guid id, bool saveChanges = true)
        {
            var entity = _db.ez_Depts.Where(p => p.DeptId == id)
                .SingleOrDefault();
            _db.ez_Depts.DeleteOnSubmit(entity);
            if (saveChanges)
            {
                SaveChanges();
            }
        }

        public void Update(Dept model, bool saveChanges = true)
        {
            var entity = _db.ez_Depts.FirstOrDefault(p => p.DeptId == model.Id);
            if (entity != null)
            {
                ModelConvert.CopyValueDept(entity, model);
            }
            if (saveChanges)
            {
                SaveChanges();
            }
        }

        #endregion

    }
}
